<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>IPC之十四：使用libdbus通过select()接收D-Bus消息的实例 - whowin - 发表我个人原创作品的技术博客</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="whowin" /><meta name="description" content="在『进程间通信』系列文章中前面已经有三篇关于D-Bus的文章，本文继续讨论D-Bus；libdbus抽象了实现IPC时实际使用的方式(管道、socket等)，libdbus允许在一个D-Bus连接上添加一个watch，通过watch对实际IPC中使用的文件描述符进行监视，本文讨论了如何在D-Bus连接中添加watch，如何使用在socket编程中常用的select从D-Bus返回的文件描述符中接收到D-Bus消息，本文给出了具体实例，附有完整的源代码；本文实例在 Ubuntu 20.04 上编译测试通过，gcc版本号为：9.4.0；本文不适合 Linux 编程的初学者阅读。
" /><meta name="keywords" content="linux, socket, hugo, dos" />






<meta name="generator" content="Hugo 0.97.3 with theme even" />


<link rel="canonical" href="https://whowin.gitee.io/post/blog/ipc/0024-select-recv-message/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.e3fea119b1980e848b03dffbeddb11dd0fba483eed0e5f11870fb8e31f145bbd.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="IPC之十四：使用libdbus通过select()接收D-Bus消息的实例" />
<meta property="og:description" content="在『进程间通信』系列文章中前面已经有三篇关于D-Bus的文章，本文继续讨论D-Bus；libdbus抽象了实现IPC时实际使用的方式(管道、socket等)，libdbus允许在一个D-Bus连接上添加一个watch，通过watch对实际IPC中使用的文件描述符进行监视，本文讨论了如何在D-Bus连接中添加watch，如何使用在socket编程中常用的select从D-Bus返回的文件描述符中接收到D-Bus消息，本文给出了具体实例，附有完整的源代码；本文实例在 Ubuntu 20.04 上编译测试通过，gcc版本号为：9.4.0；本文不适合 Linux 编程的初学者阅读。" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://whowin.gitee.io/post/blog/ipc/0024-select-recv-message/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2023-12-25T16:43:29+08:00" />
<meta property="article:modified_time" content="2023-12-25T16:43:29+08:00" />

<meta itemprop="name" content="IPC之十四：使用libdbus通过select()接收D-Bus消息的实例">
<meta itemprop="description" content="在『进程间通信』系列文章中前面已经有三篇关于D-Bus的文章，本文继续讨论D-Bus；libdbus抽象了实现IPC时实际使用的方式(管道、socket等)，libdbus允许在一个D-Bus连接上添加一个watch，通过watch对实际IPC中使用的文件描述符进行监视，本文讨论了如何在D-Bus连接中添加watch，如何使用在socket编程中常用的select从D-Bus返回的文件描述符中接收到D-Bus消息，本文给出了具体实例，附有完整的源代码；本文实例在 Ubuntu 20.04 上编译测试通过，gcc版本号为：9.4.0；本文不适合 Linux 编程的初学者阅读。"><meta itemprop="datePublished" content="2023-12-25T16:43:29+08:00" />
<meta itemprop="dateModified" content="2023-12-25T16:43:29+08:00" />
<meta itemprop="wordCount" content="5372">
<meta itemprop="keywords" content="Linux,进程间通信,D-Bus,IPC,select,DBusWatch," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="IPC之十四：使用libdbus通过select()接收D-Bus消息的实例"/>
<meta name="twitter:description" content="在『进程间通信』系列文章中前面已经有三篇关于D-Bus的文章，本文继续讨论D-Bus；libdbus抽象了实现IPC时实际使用的方式(管道、socket等)，libdbus允许在一个D-Bus连接上添加一个watch，通过watch对实际IPC中使用的文件描述符进行监视，本文讨论了如何在D-Bus连接中添加watch，如何使用在socket编程中常用的select从D-Bus返回的文件描述符中接收到D-Bus消息，本文给出了具体实例，附有完整的源代码；本文实例在 Ubuntu 20.04 上编译测试通过，gcc版本号为：9.4.0；本文不适合 Linux 编程的初学者阅读。"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

  <script async src="/js/busuanzi.pure.mini.js"></script><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9724909319263152"
     crossorigin="anonymous"></script>


</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">WhoWin</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">文章归档</li>
      </a><a href="/article-categories/categories/">
        <li class="mobile-menu-item">文章分类</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">文章标签</li>
      </a><a href="/about/about/">
        <li class="mobile-menu-item">关于</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">WhoWin</a>
  
  <div style="position:absolute; left: 80px; top: 75px; color: crimson">
      ———开源和分享是技术发展的源泉和动力；本博客所有文章均为原创
  </div>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">文章归档</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/article-categories/categories/">文章分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">文章标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/about/about/">关于</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">IPC之十四：使用libdbus通过select()接收D-Bus消息的实例</h1>

      <div class="post-meta">
        <span class="post-time"> 2023-12-25 </span>
        <div class="post-category">
            <a href="/categories/ipc/"> IPC </a>
            <a href="/categories/linux/"> Linux </a>
            <a href="/categories/c-language/"> C Language </a>
            <a href="/categories/network/"> Network </a>
            </div>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li>
      <ul>
        <li><a href="#1-基本概念">1 基本概念</a></li>
        <li><a href="#2-在d-bus中与-watch-相关的函数介绍">2 在D-Bus中与 watch 相关的函数介绍</a></li>
        <li><a href="#3-使用-select-处理-d-bus-消息的步骤">3 使用 select() 处理 D-Bus 消息的步骤</a></li>
        <li><a href="#3-实例">3 实例</a></li>
        <li><a href="#欢迎订阅-进程间通信专栏httpsblogcsdnnetwhowincategory_12404164html"><strong>欢迎订阅 <a href="https://blog.csdn.net/whowin/category_12404164.html">『进程间通信专栏』</a></strong></a></li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>在『进程间通信』系列文章中前面已经有三篇关于D-Bus的文章，本文继续讨论D-Bus；libdbus抽象了实现IPC时实际使用的方式(管道、socket等)，libdbus允许在一个D-Bus连接上添加一个watch，通过watch对实际IPC中使用的文件描述符进行监视，本文讨论了如何在D-Bus连接中添加watch，如何使用在socket编程中常用的select从D-Bus返回的文件描述符中接收到D-Bus消息，本文给出了具体实例，附有完整的源代码；本文实例在 Ubuntu 20.04 上编译测试通过，gcc版本号为：9.4.0；本文不适合 Linux 编程的初学者阅读。</p>
<h2 id="1-基本概念">1 基本概念</h2>
<ul>
<li>阅读本文前，建议先阅读前面的关于 D-Bus 的三篇文章：<a href="https://whowin.gitee.io/post/blog/ipc/0021-ipc-using-dbus/">《IPC之十一：使用D-Bus实现客户端向服务端请求服务的实例》</a>、<a href="https://whowin.gitee.io/post/blog/ipc/0022-dbus-asyn-process-signal/">《IPC之十二：使用libdbus在D-Bus上异步发送/接收信号的实例》</a> 和 <a href="https://whowin.gitee.io/post/blog/ipc/0023-dbus-resolve-hostname/">《IPC之十三：使用libdbus通过D-Bus请求系统调用实现域名解析的实例》</a></li>
<li>在文章 <a href="https://whowin.gitee.io/post/blog/ipc/0021-ipc-using-dbus/">《IPC之十一：使用D-Bus实现客户端向服务端请求服务的实例》</a> 中介绍了 D-Bus 的一些基本概念，介绍了 libdbus 库的一些基本 API，在实例中使用 libdbus 库的 APIs 实现了客户进程向服务进程请求服务的过程；</li>
<li>在文章 <a href="https://whowin.gitee.io/post/blog/ipc/0022-dbus-asyn-process-signal/">《IPC之十二：使用libdbus在D-Bus上异步发送/接收信号的实例》</a> 中，我们介绍了 D-Bus 中信号的概念，在实例中使用 libdbus 库的 match 订阅了信号，并使用过滤器(filter)异步接收信号；</li>
<li>在文章 <a href="https://whowin.gitee.io/post/blog/ipc/0023-dbus-resolve-hostname/">《IPC之十三：使用libdbus通过D-Bus请求系统调用实现域名解析的实例》</a> 中，我们介绍了如何通过 D-Bus 调用系统服务，有很多系统服务都有 D-Bus 接口，透过这个接口，应用程序可以调用系统服务，从而快速地实现一些复杂的功能；</li>
<li>在『进程间通信』系列文章中的前十篇文章中，介绍了许多 IPC 的方法，有管道、共享内存、UNIX DOMAIN SOCKET 等，其实 D-Bus 在实现 IPC 时也是用其中的一种方法实现的，但是 libdbus 将具体的实现抽象化了，所以，我们并不知道具体用的那种方法；</li>
<li>D-Bus 通过 <code>dbus-daemon</code> 来管理总线，服务进程通过一种传统 IPC 方法与 <code>dbus-daemon</code> 进行通信，客户进程可能通过另一种 IPC 方式与 <code>dbus-daemon</code> 进行通信，<code>dbus-daemon</code> 对客户进程与服务进程之间的消息进行转发；</li>
<li>实际上，我们也确实无需知道具体的实现方法，在 Linux 系统下，有所谓&quot;一切皆文件&quot;的原则，不管是管道还是 socket，最终返回给应用程序的都是一个文件描述符(File descriptor)；</li>
<li>在进行 socket 编程时，服务端在处理多个连接请求时，常常会使用 select()，将正在侦听的多个 socket 的文件描述符放到一个&rsquo;集&rsquo;中，当&rsquo;集&rsquo;中的某个文件描述符有可读数据时，select() 就会返回，然后应用程序就可以对相应的文件描述符做出处理；</li>
<li>如果在 D-Bus 编程中也能通过 select() 来处理消息的话，将给编程带来很大方便，当应用程序中要处理 D-Bus 消息、socket 通信以及文件读写时，使用 select() 可以合并处理，这将大大提高程序的效率；</li>
</ul>
<h2 id="2-在d-bus中与-watch-相关的函数介绍">2 在D-Bus中与 watch 相关的函数介绍</h2>
<ul>
<li>
<p>添加 watch 的目的就是为了监视实际实现 IPC 的文件描述符，watch 添加成功才可以获取实际使用的文件描述符，从而实现在文件描述符一级的监视；</p>
</li>
<li>
<p>libdbus 库的 API 调用手册：<a href="libdbus_api">D-Bus low-level public API</a></p>
</li>
<li>
<p>本节并不会介绍所有与 watch 相关的函数，仅介绍在本文实例中用到的函数；</p>
</li>
<li>
<p>使用 <code>dbus_bus_get()</code> 连接到 dbus-daemon，使用 <code>dbus_bus_request_name()</code> 获取总线名称都在以前的文章中做过介绍；</p>
</li>
<li>
<p><font size=5>函数 <code>dbus_connection_set_watch_functions()</code></font></p>
<ul>
<li>设置 watch 相关的函数</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">dbus_bool_t</span> <span class="n">dbus_connection_set_watch_functions</span><span class="p">(</span><span class="n">DBusConnection</span> <span class="o">*</span><span class="n">connection</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                                <span class="n">DBusAddWatchFunction</span> <span class="n">add_function</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                                <span class="n">DBusRemoveWatchFunction</span> <span class="n">remove_function</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                                <span class="n">DBusWatchToggledFunction</span> <span class="n">toggled_function</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                                <span class="kt">void</span> <span class="o">*</span><span class="n">data</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                                <span class="n">DBusFreeFunction</span> <span class="n">free_data_function</span><span class="p">)</span>	    
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>connection：通过 <code>dbus_bus_get()</code> 获取的连接</li>
<li>add_function：添加 watch 时执行的函数</li>
<li>remove_function：删除 watch 时执行的函数</li>
<li>toggled_function：切换 watch 时执行的函数</li>
<li>data：传递给 <code>add_function()</code>、<code>remove_function()</code> 和 <code>toggled_function()</code> 的用户参数；</li>
<li>free_data_function：释放 data 的函数；</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>DBusAddWatchFunction add_function</code></font></p>
<ul>
<li>
<p><strong><code>DBusAddWatchFunction</code></strong> 的定义为：<code>typedef dbus_bool_t(* DBusAddWatchFunction) (DBusWatch *watch, void *data)</code></p>
</li>
<li>
<p>所以 <code>add_function()</code> 函数的格式应该为：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">dbus_bool_t</span> <span class="nf">add_function</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">watch</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">data</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="p">........</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>当调用 <code>dbus_connection_set_watch_functions()</code> 时，<code>add_function()</code> 将被自动调用，<code>watch</code> 将由系统传递给函数，<code>data</code> 是传递给 <code>add_function()</code> 的用户数据，在调用 <code>dbus_connection_set_watch_functions()</code> 时由参数 <code>data</code> 指定；</p>
</li>
<li>
<p>watch 的数据类型是 DBusWatch，实际上就是一个结构，C 语言不是一个面向对象的语言，当要实现对象时，通常都是使用数据结构，一般情况下，无需了解其数据结构的具体情况；</p>
</li>
<li>
<p>系统传入的 <code>watch</code> 要保存好，因为在应用程序的其它地方可能需要它；</p>
</li>
<li>
<p>用户传入的 <code>data</code> 可以是任何变量或者结构，在实例中会有具体的做法；</p>
</li>
<li>
<p>在 <code>add_function()</code> 中通常需要判断 watch 是否被启用，然后通过调用 <code>dbus_watch_get_unix_fd()</code> 获取被监视的文件描述符；</p>
</li>
<li>
<p><code>add_function()</code> 返回 FALSE 时表示内存不够，所以通常情况下即便出现错误也不要返回 FALSE；</p>
</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>DBusRemoveWatchFunction remove_function</code></font></p>
<ul>
<li>
<p><strong><code>DBusRemoveWatchFunction</code></strong> 的定义为：<code>typedef void(* DBusRemoveWatchFunction) (DBusWatch *watch, void *data)</code></p>
</li>
<li>
<p>所以 <code>remove_function()</code> 函数的格式应该为：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">void</span> <span class="nf">remove_function</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">watch</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">data</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="p">........</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>在一个 watch 被禁用时，通常需要调用 <code>remove_function()</code>，一般情况下，当一个 watch 被禁用时系统会调用 <code>toggled_function()</code>，然后在 <code>toggled_function()</code> 中调用 <code>remove_funcion()</code>；</p>
</li>
<li>
<p>data 参数与 <code>add_function()</code> 中的 data 参数一样，在设置时指定；</p>
</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>DBusWatchToggledFunction toggled_function</code></font></p>
<ul>
<li>
<p><strong><code>DBusWatchToggledFunction</code></strong> 的定义为：<code>typedef void(* DBusWatchToggledFunction) (DBusWatch *watch, void *data)</code></p>
</li>
<li>
<p>所以 <code>toggled_function()</code> 函数的格式应该为：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">void</span> <span class="nf">toggled_function</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">watch</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">data</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="p">........</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>当 watch 被启用或者禁用时，系统通过调用 <code>toggled_function()</code> 来通知应用程序，系统将发生变化的 watch 作为参数传给 <code>toggled_function()</code>；</p>
</li>
<li>
<p>data 参数与 <code>add_function()</code> 中的 data 参数一样，在设置时指定；</p>
</li>
<li>
<p>在 <code>toggled_function()</code> 中，通常需要通过 <code>dbus_watch_get_enabled()</code> 判断 watch 是启用还是禁用，如果是启用，调用 <code>add_function()</code>，如果是禁用则调用 <code>remove_function()</code>；</p>
</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>dbus_watch_get_enabled()</code></font></p>
<ul>
<li>检查 watch 是否已启用</li>
</ul>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">dbus_bool_t</span> <span class="nf">dbus_watch_get_enabled</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">watch</span><span class="p">);</span>	
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>返回 TRUE 表示 watch 已经启用，FALSE 表示 watch 已经禁用；</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>dbus_watch_get_unix_fd()</code></font></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">int</span> <span class="nf">dbus_watch_get_unix_fd</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">watch</span><span class="p">);</span>	
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>返回 watch 监视的文件描述符，这个描述符可能是管道、socket，也可能是其它类型的描述符；</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>dbus_watch_get_flags()</code></font></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">unsigned</span> <span class="kt">int</span> <span class="nf">dbus_watch_get_flags</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">watch</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>获取 watch 对文件描述符的监视内容；</li>
<li>返回值可能有两个标志：<code>DBUS_WATCH_READABLE</code> 和 <code>DBUS_WATCH_WRITABLE</code>；</li>
<li><code>DBUS_WATCH_READABLE</code> 表示对文件描述符的&rsquo;读&rsquo;进行监视；</li>
<li><code>DBUS_WATCH_WRITABLE</code> 表示对文件描述符的&rsquo;写&rsquo;进行监视；</li>
<li>默认 watch 会监视文件描述符的错误状态(DBUS_WATCH_ERROR)和挂起状态(DBUS_WATCH_HANGUP)，所以这两个标志不会在这个函数的返回值中出现；</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>dbus_watch_handle()</code></font></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">dbus_bool_t</span> <span class="nf">dbus_watch_handle</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">watch</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                              <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">flags</span><span class="p">);</span>	
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>当 watch 所监视的文件描述符有可读取的数据时，需要调用此函数通知 libdbus 库；</li>
<li>当被监视的文件描述符中有数据可以读取时，调用函数 <code>dbus_watch_handle()</code> 将把数据从从文件描述符中读出，解析为 D-Bus 的消息，并把消息放入消息队列，然后才可以用 libdbus 库的 API 从队列中读出消息并进行处理，如果不调用 <code>dbus_watch_handle()</code>，则文件描述符上将一直处于有数据可读状态；</li>
<li><code>dbus_watch_handle()</code> 返回为 FALSE 时表示执行失败，执行失败的原因只有一个，就是内存不够，如果忽略返回的 FALSE，通常不会有致命问题，直至有足够内存时，<code>dbus_watch_handle()</code> 便会返回 TRUE；</li>
<li>参数 watch 为使用 <code>dbus_connection_set_watch_functions()</code> 设置的 watch，也就是系统在调用 <code>add_function()</code> 时传递过来的 watch；</li>
<li>参数 flags 与函数 <code>dbus_watch_get_flags()</code> 返回的值含义相同，<code>DBUS_WATCH_READABLE</code> 表示文件描述符中有可读数据，<code>DBUS_WATCH_WRITABLE</code> 表示文件描述符中有可写数据；</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>dbus_connection_get_dispatch_status()</code></font></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">DBusDispatchStatus</span> <span class="nf">dbus_connection_get_dispatch_status</span><span class="p">(</span><span class="n">DBusConnection</span> <span class="o">*</span><span class="n">connection</span><span class="p">);</span>	
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>获取接收消息队列的当前状态；</li>
<li>其返回值 DBusDispatchStatus 是一个枚举类型，其值有三个：
<ol>
<li><code>DBUS_DISPATCH_DATA_REMAINS</code>：表示接收消息队列中可能有消息；</li>
<li><code>DBUS_DISPATCH_COMPLETE</code>：表示接收消息队列为空；</li>
<li><code>DBUS_DISPATCH_NEED_MEMORY</code>：表示可能有消息，但如果没有更多内存，则无法确定是否有消息；</li>
</ol>
</li>
<li>当返回状态为 <code>DBUS_DISPATCH_DATA_REMAINS</code> 时，表示接收队列中有消息，或者正在将原始数据转换为 D-Bus 的消息，此时会返回 <code>DBUS_DISPATCH_DATA_REMAINS</code> 状态，但由于消息还没有解析完毕，所以队列中还没有完整的消息；</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>dbus_connection_borrow_message()</code></font></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">DBusMessage</span> <span class="o">*</span><span class="nf">dbus_connection_borrow_message</span><span class="p">(</span><span class="n">DBusConnection</span> <span class="o">*</span><span class="n">connection</span><span class="p">);</span>	
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>这个函数很有意思，它从消息队列中&quot;借用&quot;一个消息，&ldquo;借用&quot;消息和读取消息的区别在于&quot;借用&quot;的消息不会从消息队列中删除，而读取的消息会从消息队列中删除；</li>
<li>当一个消息被&quot;借用&quot;以后，这条消息尽管还在队列中，但会被锁定，其它进程(线程)将无法再读取该消息，所以&quot;借用&quot;的消息要么尽快&quot;还&quot;回来，要么尽快读取出来，否则会影响消息的处理；</li>
<li>之所以要&quot;借用&quot;消息，是因为不能确定这条消息是否应该由当前程序处理，所以要&quot;借用&quot;出来做一下判断，如果不该当前程序处理，则立即&quot;还&quot;回去，否则应该立即将该消息读出来；</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>dbus_connection_return_message()</code></font></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">void</span> <span class="nf">dbus_connection_return_message</span><span class="p">(</span><span class="n">DBusConnection</span> <span class="o">*</span><span class="n">connection</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                    <span class="n">DBusMessage</span> <span class="o">*</span><span class="n">message</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>该函数将由函数 <code>dbus_connection_borrow_message()</code> &ldquo;借用&quot;的消息&quot;还&quot;回到消息队列中；</li>
<li>参数 message 是要&quot;还&quot;回去的消息；</li>
</ul>
<hr>
</li>
<li>
<p><font size=5>函数 <code>dbus_connection_steal_borrowed_message()</code></font></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">void</span> <span class="nf">dbus_connection_steal_borrowed_message</span><span class="p">(</span><span class="n">DBusConnection</span> <span class="o">*</span><span class="n">connection</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                            <span class="n">DBusMessage</span> <span class="o">*</span><span class="n">message</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>该函数将由函数 <code>dbus_connection_borrow_message()</code> &ldquo;借用&quot;的消息从消息队列中读取出来；</li>
<li>参数 message 为要读出的消息，该函数执行完成后，该消息将从消息队列中被删除；</li>
</ul>
<hr>
</li>
<li>
<p>其它在实例中用到的函数已经在前面几篇关于 D-Bus 的文章中做过介绍，这里不再赘述；</p>
</li>
</ul>
<h2 id="3-使用-select-处理-d-bus-消息的步骤">3 使用 select() 处理 D-Bus 消息的步骤</h2>
<ul>
<li>
<p>使用 <code>dbus_bus_get()</code> 连接到 dbus-daemon，使用会话总线；</p>
</li>
<li>
<p>使用 <code>dbus_bus_request_name()</code> 设置总线名称，以便客户端可以访问到；</p>
</li>
<li>
<p>使用 <code>dbus_connection_set_watch_functions()</code> 添加一个 watch，考虑将一个结构传给设置的 watch 函数，用于存储 watch 的相关信息；</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">watch_struct</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">DBusWatch</span> <span class="o">*</span><span class="n">watched_watch</span><span class="p">;</span>   <span class="c1">// Currently used watch
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="kt">int</span> <span class="n">watched_rd_fd</span><span class="p">;</span>          <span class="c1">// Readable file descriptor being watched
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="kt">int</span> <span class="n">watched_wr_fd</span><span class="p">;</span>          <span class="c1">// Writable file descriptor being watched
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span><span class="n">watch_fds</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">dbus_connection_set_watch_functions</span><span class="p">(</span><span class="n">conn</span><span class="p">,</span> 
</span></span><span class="line"><span class="cl">                                    <span class="n">add_watch</span><span class="p">,</span> 
</span></span><span class="line"><span class="cl">                                    <span class="n">remove_watch</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                    <span class="n">toggle_watch</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">                                    <span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">watch_fds</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">))</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>为添加 watch 编写三个函数：<code>add_watch()</code>、<code>remove_watch()</code> 和 <code>toggle_watch()</code>；</p>
<blockquote>
<p><code>add_wath()</code> 中，首先使用 <code>dbus_watch_get_enabled()</code> 判断添加的 watch 是否已经启用，如未启用则无法继续，然后使用 <code>dbus_watch_get_unix_fd()</code> 获取被监视的文件描述符，使用 <code>dbus_watch_get_flags()</code> 判断被监视的这个描述符是可读还是可写，并保存好相关信息；</p>
</blockquote>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">static</span> <span class="n">dbus_bool_t</span> <span class="nf">add_watch</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">w</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">data</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">dbus_watch_get_enabled</span><span class="p">(</span><span class="n">w</span><span class="p">))</span> <span class="p">{</span>               <span class="c1">// Returns whether a watch is enabled or not.
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="k">return</span> <span class="n">TRUE</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">struct</span> <span class="n">watch_struct</span> <span class="o">*</span><span class="n">watch_fds</span> <span class="o">=</span> <span class="p">(</span><span class="k">struct</span> <span class="n">watch_struct</span> <span class="o">*</span><span class="p">)</span><span class="n">data</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kt">int</span> <span class="n">fd</span> <span class="o">=</span> <span class="n">dbus_watch_get_unix_fd</span><span class="p">(</span><span class="n">w</span><span class="p">);</span>             <span class="c1">// Returns a UNIX file descriptor to be watched, 
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                                                    <span class="c1">// which may be a pipe, socket, or other type of descriptor.
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">flags</span> <span class="o">=</span> <span class="n">dbus_watch_get_flags</span><span class="p">(</span><span class="n">w</span><span class="p">);</span>   <span class="c1">// Gets flags from DBusWatchFlags indicating what conditions 
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>                                                    <span class="c1">// should be monitored on the file descriptor.
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="k">if</span> <span class="p">(</span><span class="n">flags</span> <span class="o">&amp;</span> <span class="n">DBUS_WATCH_READABLE</span><span class="p">)</span> <span class="p">{</span>              <span class="c1">// the watch is readable
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="n">watch_fds</span><span class="o">-&gt;</span><span class="n">watched_rd_fd</span> <span class="o">=</span> <span class="n">fd</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="n">flags</span> <span class="o">&amp;</span> <span class="n">DBUS_WATCH_WRITABLE</span><span class="p">)</span> <span class="p">{</span>              <span class="c1">// the watch is writable
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>        <span class="n">watch_fds</span><span class="o">-&gt;</span><span class="n">watched_wr_fd</span> <span class="o">=</span> <span class="n">fd</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">    <span class="n">watch_fds</span><span class="o">-&gt;</span><span class="n">watched_watch</span> <span class="o">=</span> <span class="n">w</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="n">TRUE</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><blockquote>
<p><code>remove_watch()</code> 的主要作用就是在禁用 watch 时可以释放在执行 <code>add_watch()</code> 时所占用的资源；</p>
</blockquote>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">static</span> <span class="kt">void</span> <span class="nf">remove_watch</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">w</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">data</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">struct</span> <span class="n">watch_struct</span> <span class="o">*</span><span class="n">watch_fds</span> <span class="o">=</span> <span class="p">(</span><span class="k">struct</span> <span class="n">watch_struct</span> <span class="o">*</span><span class="p">)</span><span class="n">data</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="n">watch_fds</span><span class="o">-&gt;</span><span class="n">watched_watch</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="n">watch_fds</span><span class="o">-&gt;</span><span class="n">watched_rd_fd</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="n">watch_fds</span><span class="o">-&gt;</span><span class="n">watched_wr_fd</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><blockquote>
<p><code>toggle_watch()</code> 首先使用 <code>dbus_watch_get_enabled()</code> 判断系统传过来的 watch 时禁用还是启用状态，如果是禁用状态，调用 <code>remove_watch()</code>，如果是启用状态，调用 <code>add_watch()</code>；</p>
</blockquote>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">static</span> <span class="kt">void</span> <span class="nf">toggle_watch</span><span class="p">(</span><span class="n">DBusWatch</span> <span class="o">*</span><span class="n">w</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">data</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="n">dbus_watch_get_enabled</span><span class="p">(</span><span class="n">w</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">add_watch</span><span class="p">(</span><span class="n">w</span><span class="p">,</span> <span class="n">data</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">remove_watch</span><span class="p">(</span><span class="n">w</span><span class="p">,</span> <span class="n">data</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>初始化 <code>select()</code> 的文件描述符集，设置 <code>select()</code> 超时时间，执行 <code>select()</code>；</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="n">fd_set</span> <span class="n">readfds</span><span class="p">;</span>            <span class="c1">// Reading fd set, Writing fd set and ... fd set
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kt">int</span> <span class="n">max_fd</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="kt">int</span> <span class="n">activity</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">FD_ZERO</span><span class="p">(</span><span class="o">&amp;</span><span class="n">readfds</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">((</span><span class="n">watch_fds</span><span class="p">.</span><span class="n">watched_watch</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">watch_fds</span><span class="p">.</span><span class="n">watched_rd_fd</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">FD_SET</span><span class="p">(</span><span class="n">watch_fds</span><span class="p">.</span><span class="n">watched_rd_fd</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">readfds</span><span class="p">);</span>      <span class="c1">// set watched FD into fd set
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="n">max_fd</span> <span class="o">=</span> <span class="n">watch_fds</span><span class="p">.</span><span class="n">watched_rd_fd</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="n">exit</span><span class="p">(</span><span class="n">EXIT_FAILURE</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">timeval</span> <span class="n">timeoutval</span> <span class="o">=</span> <span class="p">{</span><span class="mi">5</span><span class="p">,</span> <span class="mi">0</span><span class="p">};</span>     <span class="c1">// timeout is 5 seconds
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">activity</span> <span class="o">=</span> <span class="n">select</span><span class="p">(</span><span class="n">max_fd</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">readfds</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">timeoutval</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div></li>
<li>
<p>文件描述符上有可读数据时，调用 <code>dbus_watch_handle()</code> 和消息接收函数 <code>select_recv()</code></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="n">FD_ISSET</span><span class="p">(</span><span class="n">watch_fds</span><span class="p">.</span><span class="n">watched_rd_fd</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">readfds</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="p">(</span><span class="n">dbus_watch_handle</span><span class="p">(</span><span class="n">watch_fds</span><span class="p">.</span><span class="n">watched_watch</span><span class="p">,</span> <span class="n">DBUS_WATCH_READABLE</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">select_recv</span><span class="p">(</span><span class="n">conn</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><ul>
<li>调用 <code>dbus_watch_handle()</code> 的目的是把文件描述符上的数据读出并解析为 D-Bus 消息放入消息队列；</li>
<li>如果 <code>dbus_watch_handle()</code> 返回 FALSE 表示需要更多的内存才能解析数据，此时文件描述符仍然处于有可读数据的状态，所以下次执行 <code>select()</code> 仍可以处理数据，不会有灾难后果，也可以在 <code>dbus_watch_handle()</code> 返回 FALSE 后做一个短延时(比如100ms)；</li>
</ul>
</li>
<li>
<p>接收消息程序 <code>select_recv()</code></p>
<ul>
<li>这个程序是需要自己编写的，其目的就是接收、处理消息并向客户端发送回复消息；</li>
<li>首先使用 <code>dbus_connection_get_dispatch_status()</code> 检查状态，如果不是 <code>DBUS_DISPATCH_DATA_REMAINS</code> 表示消息队列中没有消息，则不能继续进行；</li>
<li>这个接收函数的通常做法是先使用 <code>dbus_connection_borrow_message()</code> 借用消息，然后根据其消息类型、对象路径、接口名称等将消息分发给其它函数，需要丢弃的消息则将其读出直接丢弃；</li>
<li>本文实例中仅留下了需要处理的消息，实际上丢弃了所有其它的消息；</li>
<li>在这个函数中要处理到所有消息类型的消息，自行处理、分发到其他函数处理或者丢弃，不处理的话无法处理消息队列中的下一条消息；</li>
</ul>
</li>
</ul>
<h2 id="3-实例">3 实例</h2>
<ul>
<li>
<p><strong>源程序</strong>：<a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/190024/dbus-select.c">dbus-select.c</a> (<strong>点击文件名下载源程序，建议使用UTF-8字符集</strong>)演示了使用 libdbus 通过 <code>select()</code> 接收方法调用消息的过程；</p>
</li>
<li>
<p>该程序与文章 <a href="https://whowin.gitee.io/post/blog/ipc/0021-ipc-using-dbus/">《IPC之十一：使用D-Bus实现客户端向服务端请求服务的实例》</a> 中的实例 <a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/190021/dbus-methods.c">dbus-methods.c</a> 完成相同的任务，其中客户端进程的程序完全一样；</p>
</li>
<li>
<p>与 <a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/190021/dbus-methods.c">dbus-methods.c</a> 不同的是服务端进程，<a href="https://gitee.com/whowin/whowin/blob/blog/sourcecodes/190024/dbus-select.c">dbu-select.c</a> 在服务端进程为 D-Bus 连接添加了一个 watch，使用 <code>dbus_watch_get_unix_fd()</code> 从 watch 中获取实际使用的文件描述符；</p>
</li>
<li>
<p>当文件描述符上有数据可以读取时，调用接收程序读取消息并处理消息，然后向客户端发出回复消息；</p>
</li>
<li>
<p>该程序是个多进程程序，建立了一个服务端进程和若干个(默认为 3 个)客户端进程，服务端进程执行的函数为：<code>dbus-server()</code>，客户端进程执行的函数为：<code>dbus-client()</code>；</p>
</li>
<li>
<p>客户端进程向服务端进程的三个方法分别发出请求，服务端进程一一做出回复，客户端进程在调用完 <code>quit</code> 方法并收到服务端回复后主动结束进程；</p>
</li>
<li>
<p>服务端进程在收到所有客户端进程发来的对 <code>quit</code> 方法的请求消息并做出回复后主动退出进程；</p>
</li>
<li>
<p>编译：<code>gcc -Wall -g dbus-select.c -o dbus-select `pkg-config --libs --cflags dbus-1` </code></p>
</li>
<li>
<p>有关 <code>pkg-config --libs --cflags dbus-1</code> 可以参阅文章 <a href="https://whowin.gitee.io/post/blog/ipc/0021-ipc-using-dbus/">《IPC之十一：使用D-Bus实现客户端向服务端请求服务的实例》</a> 中的简要说明；</p>
</li>
<li>
<p>运行：<code>./dbus-select</code></p>
</li>
<li>
<p>运行截图：</p>
<p><img src="https://whowin.gitee.io/images/190024/dbus-select.gif" alt="Screenshot of dbus-select"></p>
</li>
</ul>
<h2 id="欢迎订阅-进程间通信专栏httpsblogcsdnnetwhowincategory_12404164html"><strong>欢迎订阅 <a href="https://blog.csdn.net/whowin/category_12404164.html">『进程间通信专栏』</a></strong></h2>
<hr>
<p><strong>欢迎访问我的博客：https://whowin.cn</strong></p>
<p><strong>email: <a href="mailto:hengch@163.com">hengch@163.com</a></strong></p>
<p><img src="https://whowin.gitee.io/images/qrcode/sponsor-qrcode.png" alt="donation"></p>
<!-- for CSDN
[article01]: https://blog.csdn.net/whowin/article/details/132171311
[article02]: https://blog.csdn.net/whowin/article/details/132171930
[article03]: https://blog.csdn.net/whowin/article/details/132172172
[article04]: https://blog.csdn.net/whowin/article/details/134869490
[article05]: https://blog.csdn.net/whowin/article/details/134869636
[article06]: https://blog.csdn.net/whowin/article/details/134939609
[article07]: https://blog.csdn.net/whowin/article/details/135015196
[article08]: https://blog.csdn.net/whowin/article/details/135074991
[article09]: https://blog.csdn.net/whowin/article/details/135143545
[article10]: https://blog.csdn.net/whowin/article/details/135212050
[article11]: https://blog.csdn.net/whowin/article/details/135281195
[article12]: https://blog.csdn.net/whowin/article/details/135332257
[article13]: https://blog.csdn.net/whowin/article/details/135332658
[article14]: https://blog.csdn.net/whowin/article/details/135493350
-->
<!-- CSDN
[img01]: https://img-blog.csdnimg.cn/img_convert/47ba719630bf63ad68877dfbdada0a73.gif
-->
    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">whowin</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2023-12-25
        
    </span>
  </p>
  
  
</div>
<footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/linux/">Linux</a>
          <a href="/tags/%E8%BF%9B%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1/">进程间通信</a>
          <a href="/tags/d-bus/">D-Bus</a>
          <a href="/tags/ipc/">IPC</a>
          <a href="/tags/select/">select</a>
          <a href="/tags/dbuswatch/">DBusWatch</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/blog/ipc/0025-resolve-arbitrary-dns-record/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">IPC之十五：使用libdbus通过D-Bus请求系统调用实现任意DNS记录解析的实例</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/blog/ipc/0023-dbus-resolve-hostname/">
            <span class="next-text nav-default">IPC之十三：使用libdbus通过D-Bus请求系统调用实现域名解析的实例</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  <span id="/post/blog/ipc/0024-select-recv-message/" class="leancloud_visitors" data-flag-title="IPC之十四：使用libdbus通过select()接收D-Bus消息的实例">
		<span class="post-meta-item-text">文章阅读量 </span>
		<span class="leancloud-visitors-count">0</span>
		<p></p>
	  </span>
  <div id="vcomments"></div>
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src='//unpkg.com/valine/dist/Valine.min.js'></script>
  <script type="text/javascript">
    new Valine({
        el: '#vcomments' ,
        appId: 'OFCGzCfJRUglzOdzrqMGkbTR-gzGzoHsz',
        appKey: 'v7P29kPAEbsmaavaYPNhGhnF',
        notify:  false ,
        verify:  false ,
        avatar:'mm',
        placeholder: '说点什么吧...',
        visitor:  true 
    });
  </script>

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:hengch@163.com" class="iconfont icon-email" title="email"></a>
  <a href="https://whowin.gitee.io/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>
<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 - 
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  <div class="busuanzi-footer">
    <span id="busuanzi_container_site_pv"> 本站总访问量 <span id="busuanzi_value_site_pv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 次 </span>
      <span class="division">|</span>
    <span id="busuanzi_container_site_uv"> 本站总访客数 <span id="busuanzi_value_site_uv"><img src="/img/spinner.svg" alt="spinner.svg"/></span> 人 </span>
  </div>

  <span class="copyright-year">
    &copy; 
    2022 - 
    2024<span class="heart"><i class="iconfont icon-heart"></i></span><span>whowin</span>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.64437849d125a2d603b3e71d6de5225d641a32d17168a58106e0b61852079683.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        }
    };
  </script>
  <script async src="https://cdn.jsdelivr.net/npm/mathjax@3.0.5/es5/tex-mml-chtml.js" integrity="sha256-HGLuEfFcsUJGhvB8cQ8nr0gai9EucOOaIxFw7qxmd+w=" crossorigin="anonymous"></script>








</body>
</html>
